/*
 * monster_list.c
 *
 *  Created on: 28 Mars. 2013
 *      Author: Sandrine Soub and Benjamin Rambaud
 */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "SDL.h"
#include "SDL_image.h"
#include "../include/constant.h"
#include "../include/game.h"
#include "../include/monster_list.h"
#include "../include/monster.h"
#include "../include/map.h"
#include "../include/bomb.h"

struct s_list {
	t_cell head;
	int size;
};

struct s_cell {
	t_monster monster;
	t_cell next;
	t_cell previous;
	Uint32 timer_monster_list;
};

t_list
monster_list_init(t_monster monster)
{
	t_list list = malloc(sizeof(*list));
	t_cell cell=malloc(sizeof(*cell));

	assert(list);
	assert(cell);

	cell->monster=monster;
	cell->next = NULL;
	cell->previous = NULL;

	list->head = cell;

	return list;
}


t_list
monster_list_add(t_list list, t_monster monster){
	assert(list);

	t_cell cell=malloc(sizeof(*cell));
	assert(cell);

	cell->monster=monster;
	cell->next=list->head;
	cell->previous=NULL;
	list->head->previous=cell;
	list->head=cell;
	list->size +=1;

	return list;
}


t_cell
monster_list_get_head(t_list list)
{
	assert(list);
	return list->head;
}

int
monster_list_get_size(t_list list)
{
	assert(list);
	return list->size;
}


t_cell
monster_list_get_next_cell(t_cell cell)
{
	assert(cell);
	return cell->next;
}


t_cell
monster_list_get_previous_cell(t_cell cell)
{
	assert(cell);
	return cell->previous;
}
t_monster
monster_list_get_type_cell(t_cell cell)
{
	assert(cell);
	return cell->monster;
}

void
monster_list_display(t_list list, SDL_Surface * screen, t_map map, t_player player){
	assert(list);
	assert(map);
	t_cell cell = monster_list_get_head(list);
	while(cell){
		monster_display(cell->monster, screen, map, player);
		cell = cell->next;
	}
}


t_list
monster_list_delete(t_list list, t_monster monster)
{
	assert(list);
	if(list){
		t_cell key=list->head;
		int found=0;

		while (key->monster != NULL && !found) {
			if(key->monster==monster) {

				if(key->previous==NULL) {
					list->head=monster_list_get_next_cell(key);
					list->head->previous=NULL;
				}

				else if(key->next==NULL) {
					key->previous->next=NULL;
				}

				else {
					key->previous->next=key->next;
					key->next->previous=key->previous;
				}
				free(key);
				found=1;
			}
			else key=monster_list_get_next_cell(key);
		}
	}
	return list;
}

t_list monster_list_from_map(t_map map, t_list monster_list){
	//assert(map);
	int i, j;

	for(i=0; i < map_get_width(map); i++){
		for(j=0; j < map_get_height(map); j++){
			if(map_get_cell_type(map, i, j)==CELL_MONSTER){
				if(!monster_list)
					monster_list=monster_list_init(monster_init(i,j));
				else monster_list_add(monster_list, monster_init(i,j));
			}
		}
	}
	return monster_list;
}

